package com.youlai.boot.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.boot.common.excel.ExcelOperationService;
import com.youlai.boot.common.result.ExcelResult;
import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.system.model.entity.Bigcap;
import com.youlai.boot.system.model.form.BigcapForm;
import com.youlai.boot.system.model.query.BigcapQuery;
import com.youlai.boot.system.service.BigcapService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import java.util.Arrays;

/**
 * 大盘底表控制器
 *
 * @author xiheforever
 * @since 2025-05-16 23:10
 */
@Tag(name = "大盘底接口", description = "提供大盘数据的增删改查和Excel导入导出功能")
@RestController
@RequestMapping("/api/v1/bigcap")
@RequiredArgsConstructor
public class BigcapController {

    private final BigcapService bigcapService;
    private final ExcelOperationService excelOperationService;

    @Operation(summary = "获取分页列表")
    @GetMapping("/page")
    public PageResult<Bigcap> getPageList(BigcapQuery queryParams) {
        Page<Bigcap> page = bigcapService.page(new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                new LambdaQueryWrapper<>());
        return PageResult.success(page);
    }

    @Operation(summary = "大盘底表详情")
    @GetMapping("/{id}")
    public Result<Bigcap> getDetail(
            @Parameter(description = "大盘底表ID") @PathVariable Long id
    ) {
        Bigcap entity = bigcapService.getById(id);
        return Result.success(entity);
    }

    @Operation(summary = "新增大盘底")
    @PostMapping("/add")
    public Result<Boolean> add(
            @Valid @RequestBody BigcapForm formData
    ) {
        boolean result = bigcapService.saveBigcap(formData);
        return Result.judge(result);
    }

    @Operation(summary = "获取大盘底表单数据")
    @GetMapping("/{id}/form")
    @PreAuthorize("@ss.hasPerm('system:bigcap:edit')")
    public Result<BigcapForm> getBigcapForm(
        @Parameter(description = "大盘底ID") @PathVariable Long id
    ) {
        BigcapForm formData = bigcapService.getBigcapFormData(id);
        return Result.success(formData);
    }

    @Operation(summary = "修改大盘底")
    @PutMapping(value = "/{id}")
    @PreAuthorize("@ss.hasPerm('system:bigcap:edit')")
    public Result<Void> updateBigcap(
            @Parameter(description = "大盘底ID") @PathVariable Long id,
            @RequestBody @Validated BigcapForm formData
    ) {
        boolean result = bigcapService.updateBigcap(id, formData);
        return Result.judge(result);
    }

    @Operation(summary = "删除大盘底")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('system:bigcap:delete')")
    public Result<Void> deleteBigcaps(
        @Parameter(description = "大盘底ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = bigcapService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.judge(result);
    }

    @Operation(
        summary = "导出大盘数据",
        description = "根据查询条件导出大盘数据Excel文件",
        tags = {"excel", "bigcap", "export"}
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200",
            description = "导出成功，返回Excel文件流",
            content = @Content(mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE)
        ),
        @ApiResponse(
            responseCode = "500",
            description = "导出失败",
            content = @Content
        )
    })
    @GetMapping("/export")
    public void exportExcel(
        @Parameter(description = "查询参数，支持日期范围等过滤条件") BigcapQuery queryParams,
        HttpServletResponse response
    ) {
        excelOperationService.exportExcel(queryParams, "bigcap", response);
    }

    @Operation(
        summary = "导入大盘数据",
        description = "导入Excel文件中的大盘数据",
        tags = {"excel", "bigcap", "import"}
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200",
            description = "导入成功，返回导入结果",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON_VALUE,
                schema = @Schema(implementation = Result.class)
            )
        ),
        @ApiResponse(
            responseCode = "400",
            description = "导入失败，文件格式错误",
            content = @Content
        ),
        @ApiResponse(
            responseCode = "500",
            description = "导入失败，服务器错误",
            content = @Content
        )
    })
    @PostMapping("/import")
    public Result<ExcelResult> importExcel(
        @Parameter(
            description = "Excel文件，仅支持.xlsx格式",
            required = true,
            content = @Content(mediaType = MediaType.MULTIPART_FORM_DATA_VALUE)
        )
        @RequestParam("file") MultipartFile file
    ) {
        ExcelResult result = excelOperationService.importExcel(file, "bigcap");
        return Result.success(result);
    }

    @Operation(
        summary = "下载大盘数据导入模板",
        description = "下载用于导入大盘数据的Excel模板",
        tags = {"excel", "bigcap", "template"}
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200",
            description = "下载成功，返回Excel文件流",
            content = @Content(mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE)
        ),
        @ApiResponse(
            responseCode = "500",
            description = "下载失败，服务器错误",
            content = @Content
        )
    })
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        excelOperationService.downloadTemplate("bigcap", response);
    }
}
